import { clsx, type ClassValue } from 'clsx'
import { twMerge } from 'tailwind-merge'
import relativeTime from 'dayjs/plugin/relativeTime'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import localizedFormat from 'dayjs/plugin/localizedFormat'

dayjs.extend(relativeTime)
dayjs.extend(localizedFormat)

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}

/**
 * 把时间戳转换成指定格式
 * @param timestamp 时间戳
 * @param format
 * @returns
 */
export function formatDate(timestamp: number | string | Date, format = ''): string {
  if (!timestamp) return ''
  const date = new Date(timestamp)

  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0') // 月份从0开始，需要加1
  const day = date.getDate().toString().padStart(2, '0')
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  const seconds = date.getSeconds().toString().padStart(2, '0')

  if (format === 'YYYY-MM-DD') {
    return `${year}-${month}-${day}`
  } else if (format === 'HH:MM:SS') {
    return `${hours}:${minutes}:${seconds}`
  } else if (format === '年月日时分秒') {
    return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`
  } else if (format === '年月日') {
    return `${year}年${month}月${day}日`
  } else {
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }
}

export function formatTime(date: Date): string {
  const now = new Date()
  const diff = now.getTime() - date.getTime()

  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))

  if (minutes < 3) {
    return '刚刚'
  } else if (minutes < 10) {
    return '10分钟前'
  } else if (hours < 1) {
    return '1小时前'
  } else if (days < 1) {
    return '1天前'
  } else if (days <= 7) {
    return `${days}天前`
  } else {
    return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
  }
}

export function formatRelativeTime(date: Date): string {
  const now = dayjs()
  const targetDate = dayjs(date, {
    // locale: 'zh-cn',
  })
  const diffDays = now.diff(targetDate, 'day')

  if (diffDays >= 7) {
    return targetDate.format('LL LT')
  }

  return targetDate.fromNow()
}

// // 示例用法
// const date = new Date(new Date().getTime() - 2 * 60 * 1000); // 2分钟前
// console.log(formatTime(date)); // 输出: 刚刚

export function getChangeIndex(textValue: string, newText: string) {
  /* 找出两个文字有哪里不同， 找出不同的地方 newText 与 textValue 进行比较 */
  /* 找出两个文字有哪里不同， 找出不同的地方 newText 与 textValue 进行比较 */
  const diffStartIndex = newText.split('').findIndex((char, index) => {
    return char !== textValue[index]
  })

  const diffEndIndex = newText
    .split('')
    .reverse()
    .findIndex((char, index) => {
      return char !== textValue[textValue.length - index - 1]
    })

  console.log('🚀 ~ handleTextOperation ~ diffIndex:', diffStartIndex, diffEndIndex)

  let startIndex = 0
  let endIndex = 0

  if (diffStartIndex === -1) {
    // 前面开始位置是0
    startIndex = 0
  } else {
    startIndex = diffStartIndex
  }

  if (diffEndIndex === -1) {
    // 结束位置不存在，说明后面的文字全部不同
    endIndex = newText.length
  } else {
    endIndex = newText.length - diffEndIndex
  }
  console.log('start:', startIndex, 'end:', endIndex)
  return {
    startIndex,
    endIndex,
  }
}

export const sleep = (ms: number = 0) => {
  return new Promise((resolve) => setTimeout(resolve, ms))
}

export const copyToClipboard = () => {
  // // 创建一个不可见的文本区域
  // const textArea = document.createElement('textarea')
  // textArea.value = text
  // document.body.appendChild(textArea)

  // // 选择文本区域的内容
  // textArea.select()
  // textArea.setSelectionRange(0, 99999) // 对于移动设备

  // // 复制文本到剪贴板
  // try {
  //   document.execCommand('copy')
  //   console.log('Text copied to clipboard')
  // } catch (err) {
  //   console.error('Failed to copy text: ', err)
  // }

  // // 移除文本区域
  // document.body.removeChild(textArea)

  const contentElement = document.getElementById('content')
  const range = document.createRange()
  if (contentElement) {
    range.selectNodeContents(contentElement)
    const selection = window.getSelection()
    if (selection) {
      selection.removeAllRanges()
      selection.addRange(range)

      try {
        document.execCommand('copy')
        console.log('Content copied to clipboard')
      } catch (err) {
        console.error('Unable to copy content to clipboard', err)
      }

      // 清除选中的内容
      selection.removeAllRanges()
    }
  }
}
export function isMobileDevice() {
  if (typeof window !== 'undefined') {
    const screenWidth = window.innerWidth || document.documentElement.clientWidth

    // 通常认为小于 768px 的屏幕宽度是移动设备
    return screenWidth < 768
  }
  return true
}
